package com.hnchances.wjb.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hnchances.wjb.Service.Impl.UserServiceImpl;
import com.hnchances.wjb.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.Authenticator;
//自定义的UserRealm类
public class UserRealm11 extends AuthorizingRealm {
    @Autowired
    UserServiceImpl userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        info.addStringPermission("user:add");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        LambdaQueryWrapper<User> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getTrueName,usernamePasswordToken.getUsername());
        User user = userService.getOne(lambdaQueryWrapper);
        if (user==null){
            return null;  //抛出异常UnknownAccountException
        }

        //密码认证 shiro做
        return new SimpleAuthenticationInfo(user,user.getPassWord(),"");
    }
}
